package com.lsq.baseadmin.modules.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsq.baseadmin.common.enums.SwitchEnum;
import com.lsq.baseadmin.modules.manage.entity.Department;
import com.lsq.baseadmin.modules.manage.mapper.DepartmentMapper;
import com.lsq.baseadmin.modules.manage.service.DepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsq
 * @since 2020-10-27
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Department department) {
        baseMapper.updateById(department);
        disableChildren(department);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Department department) {
        baseMapper.updateById(department);
        disableChildren(department);
    }

    @Override
    public List<Department> list(Department department) {
        QueryWrapper<Department> wrapper = createWrapper(department);
        return baseMapper.selectList(wrapper);
    }

    private void disableChildren(Department department) {
        // 如果是禁用， 要把其子部门全都禁用
        if (SwitchEnum.DISABLE.getValue().equals(department.getStatus())) {
            Department child = new Department();
            child.setStatus(SwitchEnum.DISABLE.getValue());
            QueryWrapper<Department> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", department.getId());
            baseMapper.update(child, wrapper);
        }
    }

    private QueryWrapper<Department> createWrapper(Department department) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        if(null == department) {
            return wrapper;
        }

        if(StringUtils.hasText(department.getName())) {
            wrapper.like("name", department.getName());
        }

        return wrapper;
    }
}
